<?php
class Update_model
extends CI_Model
    {
    private $HT;
    public $countValidPlayers = 0;
    public $errors = array();

    function __construct() { parent::__construct(); }

    function update_players()
        {
        //$user=$this->input->post('ht_login', TRUE);
        //$pass=$this->input->post('ht_pass', TRUE);

        //if (!$user || !$pass)
        //    return false;

        if (!$this->auth->isAuthorised()) return false;
        
        $this->load->library('PHT');
        $this->load->config('CHPP');
        //$this->HT=new CHPPConnection($this->config->item('CHPP_App_Name'), $this->config->item('CHPP_num'),
        //                             $this->config->item('CHPP_key'),      $this->config->item('CHPP_cookie_path'));

        $this->HT = new CHPPConnection($this->config->item('consumerKey'), $this->config->item('consumerSecret'));
        
        $userToken = $this->session->userdata('usrTok');
        $userTokenSecret =  $this->session->userdata('usrTokSec');
        $this->HT->setOauthToken($userToken);
        $this->HT->setOauthTokenSecret($userTokenSecret);
        
        //$teat = $this->HT->checkToken($userToken, $userTokenSecret);
        
        $flag_connected = (int) $this->HT->getClub()->getUserId(); //проверяем, можем ли мы получить данные из ХТ
        //if ($this->auth->ht_login($user, $pass, $this->HT))
          if ($flag_connected)  
            {
            if ($this->isNotPlayMatch()) //если команда сейчас не играет матчи и доступна вся информация
                {
                ///////////забиваем данные об игроках
                $teamPlayers=$this->HT->getTeamPlayers();
                $players    =$this->parsePlayers($teamPlayers);
                $this->view->set('parsedPlayers', $this->_renderTable($players));

                if ($this->countValidPlayers) //если есть игроки, которые подходят трекеру
                    {
                    $valid_players=$this->_getValidPlayers($players);
                    $this->checkSoldPlayers($valid_players);

                    $teamDetails =$this->HT->getTeam($this->HT->getClub()->getTeamId());
                    $teamPersonal=$this->HT->getClub()->getSpecialists();

                    $this->parseTeamDetails($teamDetails, $teamPersonal);
                    
                    //забиваем данные матчей
                    $teamMatches=$this->HT->getSeniorTeamMatches(); 
                    
                    $this->parseTeamMatches($teamMatches, $valid_players);
                    
                    //забиваем тренировку
                    $training=$this->HT->getTraining();
                    
                    $this->parseTraining($training);
                    }
                }

            $this->view->set('result', 'Success');
            //$this->HT->disconnect();
            
            }
        else
            {
            $this->view->set('result', 'False to login');
            }
        }

    function _getValidPlayers($players)
        {
        $player_array=array();

        foreach ($players as $player)
            {
            if ($player['result'])
                $player_array[]=$player['PlayerID'];
            }

        return $player_array;
        }

    function isNotPlayMatch()
        {
        if (!$this->HT)
            return false; //если не определен HT

        if ($this->HT->getTraining()->getTeamSpirit() != NULL)
            return true;
        else
            return false;
        }

    function parsePlayers($teamPlayers)
        {
        $parsed=array();

        for ($i=1; $i <= $teamPlayers->getNumberPlayers(); $i++)
            {
            $playerData=array();

            $parsed[$i]['PlayerID']  =$teamPlayers->getPlayer($i)->getId();
            $parsed[$i]['PlayerName']=$teamPlayers->getPlayer($i)->getName();
            $parsed[$i]['CountryID'] =$teamPlayers->getPlayer($i)->getCountryId();
            $parsed[$i]['result']    =false;

            if ($parsed[$i]['CountryID'] == 62) //если игрок - украинец
                {
                //Проверяем время последнего обновления информации по игроку
                /*****************/
                /*
                if (!$this->checkLastUpdate(
                         $this->HT->getClub()->getXml()->getElementsByTagName("FetchedDate")->item(0)->nodeValue,
                         $parsed[$i]['PlayerID']))
                    {
                    $this->errors['player'][$i][]
                        =$parsed[$i]['result_info']='Информация об игроке ID' . $parsed[$i]['PlayerID']
                        . ' обновлялась менее трех часов назад!';
                    continue;
                    }
                */   
                /*************************/
                
                //массив данных об игроке
                $playerDetails
                    =$this->HT->getPlayer($parsed[$i]['PlayerID']); //получаем расширенную информацию об игроке 

                    
                if ($this->isPlayerValid($playerDetails) && $playerDetails->isSkillsAvailable())
                    {
                    $this->countValidPlayers++;
                    $playerData
                        =$this->getPlayer($teamPlayers->getPlayer($i), $playerDetails); //получаем данные об игроке
                    }
                else
                    {
                    $parsed[$i]['result_info']='Не прошел по параметрам';
                    continue;
                    }

                unset ($playerDetails);

                if (!$playerData)
                    {
                    $this->errors['player'][$i][]
                        =$parsed[$i]['result_info']="Ошибка получения данных об игроке ID " . $teamPlayers->getPlayer(
                                                                                                  $i)->getId();
                    continue; //если ошибка продолжаем цикл
                    }

                $this->db->set($playerData);
                $query=$this->db->query(
                           "SELECT `PlayerID` FROM `Players` WHERE (`PlayerID`=" . $playerData['PlayerID'] . ")");

                if ($query->num_rows() == 0) //если такого игрока нет в БД
                    {
                    $this->db->insert('Players');
                    }
                else
                    {
                    $this->db->where('PlayerID', $playerData['PlayerID']);
                    $this->db->update('Players', $playerData);
                    }

                //////////Забиваем категорию
                $this->setPlayerCategory($playerData);
                ///////////////////////


                /////////////////игроков в таблицу истории данных
                $date_arr              =date_parse($playerData['FetchDate']);
                $playerData['Data']    =$date_arr['year'] . '-' . $date_arr['month'] . '-' . $date_arr['day'];
                $playerData['DataTime']=$date_arr['hour'] . ':' . $date_arr['minute'] . ':' . $date_arr['second'];
                unset ($date_arr);
                $playerData['Season']  =$this->HT->getLeagueSeason()->getSeason();
                $playerData['Week']    =$this->HT->getWorldDetails()->getLeague(
                                            $this->HT->getLeague()->getLeagueId())->getMatchRound();
                /****ПЕРЕПРИСВАИВАНИЕ ПОЛЕЙ - УБРАТЬ ПРИ ПЕРЕЕЗДЕ НА НОВЫЙ ТРЕКЕР!!!!!!****/
                $playerData['TeamID']  =$playerData['OwningTeam'];
                $playerData['TeamName']=$playerData['OwningTeamName'];
                unset($playerData['PlayerName'], $playerData['FetchDate'], $playerData['OwningTeam'],
                      $playerData['OwningTeamName']);
                
                $this->db->set($playerData);

                if ($this->db->insert('Players_Details'))
                    {
                    $parsed[$i]['result']     =true;
                    $parsed[$i]['result_info']='Успешно обновлено';
                    }
                else
                    {
                    $parsed[$i]['result_info']='Ошибка внесения в историю игрока ID ' . $parsed[$i]['PlayerID'];
                    }
                } //END IF игрок - украинец
            else
                {
                $parsed[$i]['result_info']='Не то гражданство';
                }
            } //END FOR 

        return $parsed;
        }

    function getPlayer($player, $playerDetails)
        {
        $data=array();

        if (!$player->getName())
            return $data;

        $data=array
            (
            'PlayerID'        => $player->getId(),
            'PlayerName'      => $player->getName(),
            'PlayerNumber'    => $player->getShirtNumber(),
            'Age'             => $player->getAge(),
            'AgeDays'         => $player->getDays(),
            'TSI'             => $player->getTsi(),
            'PlayerForm'      => $player->getForm(),
            'Statement'       => $player->getStatement(),
            'Experience'      => $player->getExperience(),
            'Leadership'      => $player->getLeadership(),
            'Salary'          => $player->getSalary(HTMoney::Ukraina),
            'IsAbroad'        => $player->isAbroad(),
            'Agreeability'    => $player->getAgreeability(),
            'Aggressiveness'  => $player->getAggressiveness(),
            'Honesty'         => $player->getHonesty(),
            'LeagueGoals'     => $player->getGoalsInLeague(),
            'CupGoals'        => $player->getGoalsInCup(),
            'FriendliesGoals' => $player->getGoalsInFriendly(),
            'CareerGoals'     => $player->getGoalsInCareer(),
            'CareerHattricks' => $player->getHattricksInCareer(),
            'Specialty'       => $player->getSpeciality(),
            'TransferListed'  => $player->isTransferListed(),
            'NationalTeamID'  => $player->getNationalTeamId(),
            'Cards'           => $player->getCards(),
            'InjuryLevel'     => $player->getInjury(),
            'StaminaSkill'    => $playerDetails->getStamina(),
            'KeeperSkill'     => $playerDetails->getKeeper(),
            'PlaymakerSkill'  => $playerDetails->getPlaymaker(),
            'ScorerSkill'     => $playerDetails->getScorer(),
            'PassingSkill'    => $playerDetails->getPassing(),
            'WingerSkill'     => $playerDetails->getWinger(),
            'DefenderSkill'   => $playerDetails->getDefender(),
            'SetPiecesSkill'  => $playerDetails->getSetPieces(),
            'OwningTeam'      => $playerDetails->getTeamId(),
            'OwningTeamName'  => $playerDetails->getTeamName(),
            'TrainerType'     => $playerDetails->getTrainerType(),
            'TrainerSkill'    => $playerDetails->getTrainerSkill(),
            'CountryID'       => $player->getCountryId(),
            'NativeLeagueID'  => $playerDetails->getNativeLeagueId(),
            'Caps'            => $playerDetails->getACaps(),
            'CapsU20'         => $playerDetails->getU20Caps(),
            'FetchDate'       => $this->HT->getClub()->getXml()->getElementsByTagName("FetchedDate")->item(0)->nodeValue
            );

        $data=$this->_prepare_query($data);

        return $data;
        }

    function isPlayerValid($playerDetails)
        {
        $requirements=array
            (
            17 => 6,
            18 => 8,
            19 => 10,
            20 => 11,
            21 => 12,
            22 => 13,
            23 => 14,
            24 => 14
            );

        $Age=$playerDetails->getAge();

        if ($Age > 23 && $Age <= 33)
            $Age=24;

        if ($Age > 33)
            return false;

        $skills=array
            (
            'getKeeper',
            'getPlaymaker',
            'getScorer',
            'getPassing',
            'getWinger',
            'getDefender',
            'getSetPieces'
            );

        foreach ($skills as $getSkill)
            {
            $skill = $playerDetails->$getSkill();

            if ($playerDetails->$getSkill() >= $requirements[$Age])
                return true;
            }

        return false;
        }

    function setPlayerCategory($data = '')
        {
        if (!$data)
            return false;

        $skills['1']=$data['KeeperSkill'];
        $skills['2']=$data['DefenderSkill'];
        $skills['7']=$data['PlaymakerSkill'];
        $skills['4']=$data['WingerSkill'];
        //$skills['3']=$playerDetails->getPassing();
        $skills['5']=$data['ScorerSkill'];
        //$skills['6']=$playerDetails->getSetPieces();

        arsort ($skills);
        $big        =current($skills);
        $key        =key($skills);

        $query      =$this->db->query(
                         "SELECT `PlayerID` FROM `Player_categories` WHERE (`PlayerID`=" . $data['PlayerID']
                             . " AND `MainCategoryID`=1)");

        if ($query->num_rows == 0)
            {
            $sql="INSERT INTO `Player_categories` (`PlayerID`, `CategoryID`, `MainCategoryID`) VALUES ("
                . $data['PlayerID'] . ", $key, 1)";
            }
        else
            {
            $sql="UPDATE `Player_categories` SET `CategoryID`=$key WHERE (`PlayerID`=" . $data['PlayerID']
                . " AND `MainCategoryID`=1)";
            }

        if ($this->db->query($sql))
            return true;
        else
            return false;
        }

    function checkLastUpdate($fetchDate, $PlayerID)
        {
            
        $period  =60 * 60 * 3;
        $date_arr=date_parse($fetchDate);
        $date    =$date_arr['year'] . '-' . $date_arr['month'] . '-' . $date_arr['day'];
        $time    =$date_arr['hour'] . ':' . $date_arr['minute'] . ':' . $date_arr['second'];
        unset ($date_arr);
        $str     ="SELECT `Data`, `DataTime` FROM `Players_Details` WHERE 
                            (`PlayerID`='" . $PlayerID . "' AND `Data`='" . $date . "' AND 
                            (TIME_TO_SEC(TIMEDIFF('" . $date . " " . $time . "', CONCAT(`Data`, ' ', `DataTime`)))<(" . $period . "))
                            )";
        $query   =$this->db->query($str);

        if ($query->num_rows == 0) //если последний раз апдейтили не раньше трех часов назад 
            return true;
        else
            return false;
        }

    function checkSoldPlayers($valid_players)
        {
        //проверяем, нет ли проданных игроков
        $sql  ="SELECT `PlayerID` FROM `Players` WHERE (`OwningTeam`= " . $this->HT->getClub()->getTeamId() . ")";
        $query=$this->db->query($sql);

        if ($query->num_rows() > 0)
            {

            //так как $player_array не будет пустой (изначально при вызове функции происходит проверка), то тут проверки не делаем    
            foreach ($query->result_array()as $temp)
                {
                $sold = array_search($temp['PlayerID'], $valid_players);

                if ($sold === false)
                    {
                    try 
                    {
                    $soldTeamID  =$this->db->escape($this->HT->getPlayer($temp['PlayerID'])->getTeamId());
                    $soldTeamName=$this->db->escape($this->HT->getTeam($soldTeamID)->getTeamName());
                    $sql="UPDATE `Players` SET `sold`='1', `soldTeamID`=$soldTeamID ,`soldTeamName`=$soldTeamName
                           WHERE (`PlayerID`=" . $temp['PlayerID'] . ")";

                    /*ALTER TABLE `Players` ADD `sold` TINYINT NOT NULL AFTER `FetchDate` ,
                    ADD `soldTeamID` INT NOT NULL AFTER `sold` ,
                    ADD `soldTeamName` VARCHAR( 255 ) NOT NULL AFTER `soldTeamID` ;*/
                    }
                    catch (HTError $e)
                    {
                    continue;    
                    }
                    
                    }
                else
                    {
                    $sql="UPDATE `Players` SET `sold`='0' , `soldTeamID`='0' , `soldTeamName`=''
                         WHERE (`PlayerID`=" . $temp['PlayerID'] . ")";
                    }

                $this->db->query($sql);
                }
            }
        }

    function parseTeamDetails($teamDetails, $teamPersonal)
        {
        $data=array
            (
            'TeamID'                 => $teamDetails->getTeamId(),
            'TeamName'               => $teamDetails->getTeamName(),
            'ShortTeamName'          => $teamDetails->getShortTeamName(),
            'UserID'                 => $teamDetails->getUserId(),
            'ArenaID'                => $teamDetails->getArenaId(),
            'CountryID'              => $teamDetails->getLeagueId(),
            'RegionID'               => $teamDetails->getRegionId(),
            'TrainerPlayerID'        => $teamDetails->getTrainerId(),
            'HomePage'               => $teamDetails->getHomePageUrl(),
            'CupID'                  => $teamDetails->getCupId(),
            'StillInCup'             => $teamDetails->isInCup(),
            'CupName'                => $teamDetails->getCupName(),
            'LeagueLevelUnitID'      => $teamDetails->getLeagueLevelId(),
            'LeagueLevelUnitName'    => $teamDetails->getLeagueLevelName(),
            'NumberOfVictories'      => $teamDetails->getNumberOfVitories(),
            'NumberOfUndefeated'     => $teamDetails->getNumberOfUndefeat(),
            'LogoURL'                => $teamDetails->getLogoUrl(),
            'FanclubID'              => $teamDetails->getFanClubId(),
            'FanclubName'            => $teamDetails->getFanClubName(),
            'NumberOfGuestbookItems' => $teamDetails->getNumberMessageInGuestbook(),
            'Dress'                  => '',//$teamDetails->getDressCode(),
            'DressAlternate'         => '',//$teamDetails->getDressAlternateCode(),
            'IsBot'                  => $teamDetails->isBot(),
            'BotSince'               => $teamDetails->getBotDate(),
            'TeamRank'               => $teamDetails->getTeamRank(),
            'FetchedDate'            => $this->HT->getClub()->getXml()->getElementsByTagName(
                                            "FetchedDate")->item(0)->nodeValue,
            'AssistantTrainers'      => $teamPersonal->getAssistantTrainers(),
            'KeeperTrainers'         => '',//$teamPersonal->getKeeperTrainers(),
            'Psychologists'          => $teamPersonal->getPsychologists(),
            'PressSpoken'            => $teamPersonal->getPressSpoken(),
            'Economists'             => '',//$teamPersonal->getEconomists(),
            'Physiotherapists'       => $teamPersonal->getPhysiotherapists(),
            'Doctors'                => $teamPersonal->getDoctors()
            );

        $data=$this->_prepare_query($data);
        
        $this->db->set($data);
        $query=$this->db->query(
                   "SELECT `TeamID` FROM `TeamDetails` WHERE `TeamID`=" . $this->db->escape($data['TeamID']));

        if ($query->num_rows() == 0) //если такой команды еще нет в БД
            {
            $this->db->insert('TeamDetails');
            }
        else
            {
            $this->db->where('TeamID', $data['TeamID']);
            $this->db->update('TeamDetails', $data);
            }

        //////////////////////////////забиваем данные в teamPersonal 
        $data=array
            (
            'TeamID'            => $teamDetails->getTeamId(),
            'TeamName'          => $teamDetails->getTeamName(),
            'TrainerPlayerID'   => $teamDetails->getTrainerId(),
            'FetchedDate'       => $this->HT->getClub()->getXml()->getElementsByTagName("FetchedDate")->item(0)->nodeValue,
            'AssistantTrainers' => $teamPersonal->getAssistantTrainers(),
            'KeeperTrainers'    => '',//$teamPersonal->getKeeperTrainers(),
            'Psychologists'     => $teamPersonal->getPsychologists(),
            'PressSpoken'       => $teamPersonal->getPressSpoken(),
            'Economists'        => '',//$teamPersonal->getEconomists(),
            'Physiotherapists'  => $teamPersonal->getPhysiotherapists(),
            'Doctors'           => $teamPersonal->getDoctors()
            );

        $data=$this->_prepare_query($data);
        
        $this->db->set($data);
        $this->db->insert('TeamPersonal_history');
        }

    function parseTeamMatches($teamMatches, $valid_players)
        {
        for ($j=1; $j < $teamMatches->getNumberMatches(); $j++)
            { //получаем расстановки
            $match = $teamMatches->getMatch($j);

            $data=array
                (
                'MatchID'      => $match->getId(),
                'MatchType'    => $match->getType(),
                'MatchDate'    => $match->getDate(),
                'HomeTeamID'   => $match->getHomeTeamId(),
                'HomeTeamName' => $match->getHomeTeamName(),
                'AwayTeamID'   => $match->getAwayTeamId(),
                'AwayTeamName' => $match->getAwayTeamName(),
                'Status'       => $match->getStatus(),
                );

            $data=$this->_prepare_query($data);

            $this->db->set($data);
            $query=$this->db->query(
                       "SELECT `MatchID` FROM `Matches` WHERE `MatchID`=" . $this->db->escape($data['MatchID']));

            if ($query->num_rows() == 0)
                {
                $this->db->insert('Matches');
                }
            else
                {
                $this->db->where('MatchID', $data['MatchID']);
                $this->db->update('Matches', $data);
                }

            ///////////////// Забиваем данные расстановок
            $lineUP=$this->HT->getSeniorLineup($data['MatchID']);

            for ($k=1; $k < $lineUP->getPlayersNumber(); $k++)
                {
                $line_player = $lineUP->getPlayer($k);
                $pid         =$line_player->getId();

                $data=array();

                if (array_search($pid, $valid_players))
                    { //если игрок подходит по данным
                    $data=array
                        (
                        'PlayerID'                => $line_player->getId(),
                        'MatchID'                 => $lineUP->getMatchId(),
                        'Position'                => (int)$line_player->getPosition(),
                        'IndividualOrder'         => (int)$line_player->getIndividualOrder(),
                        'RatingStars'             => (float)$line_player->getRatingStars(),
                        'RatingStarsAtEndOfMatch' => (float)$line_player->getRatingStarsAtEndOfMatch(),
                        'Role'                    => (int)$line_player->getRole(),
                        );

                    $data=$this->_prepare_query($data);

                    $this->db->set($data);

                    $query=$this->db->query(
                               "SELECT `PlayerID` FROM `Players_lineups` WHERE (`PlayerID`=" . $data['PlayerID']
                                   . " AND `MatchID`=" . $data['MatchID'] . ")");

                    if ($query->num_rows() == 0)
                        {
                        $this->db->insert('Players_lineups');
                        }
                    else
                        {
                        $this->db->where('PlayerID', $data['PlayerID']);
                        $this->db->where('MatchID', $data['MatchID']);
                        $this->db->update('Players_lineups', $data);
                        }
                    }
                } //Забиваем данные расстановок
            }
        }

    function parseTraining($training)
        {
        
           
         $data=array(
         'FetchDate'     =>$training->getXml()->getElementsByTagName("FetchedDate")->item(0)->nodeValue,
         'FetchTime'   =>  $training->getXml()->getElementsByTagName("FetchedDate")->item(0)->nodeValue,
         'TeamID'      =>  $training->getTeamId(),
         'TeamName'      =>  $training->getTeamName()  ,
         'TrainingLevel'   =>  $training->getTrainingLevel() ,
         'NewTrainingLevel'  => $training->getNewTrainingLevel()   ,
         'TrainingType'      =>  $training->getTrainingType(),
         'StaminaTrainingPart' => $training->getStaminaTrainingPart(),
         'TrainerID'          =>  $training->getTrainerId(),
         'TrainerName'        =>  $training->getTrainerName(),
         'ArrivalDate'        =>  $training->getTrainerArrivalDate(),
         'TrainerSkill'       =>  $this->HT->getPlayer($training->getTrainerId())->getTrainerSkill(),
         'TrainerType'        =>  $this->HT->getPlayer($training->getTrainerId())->getTrainerType(),
         'Morale'             =>  $training->getTeamSpirit(),
         'SelfConfidence'     =>  $training->getSelfConfidence(),
         'Experience433'      =>  $training->get433Experience(),
         'Experience451'      =>  $training->get451Experience(),
         'Experience352'      =>  $training->get352Experience(),
         'Experience532'      =>  $training->get532Experience(),
         'Experience343'      =>  $training->get343Experience(),
         'Experience541'      =>  $training->get541Experience(),
         );
         
                   $data=$this->_prepare_query($data);                   
                   
                   $this->db->set($data);
                   
                   $query=$this->db->query("SELECT `TeamID` FROM `Training` WHERE (`TeamID`=" . $data['TeamID'] . ")");
                    
                   
                    if ($query->num_rows()== 0)
                        {
                            $this->db->insert('Training');
                        }
                    else
                        {
                           $this->db->where('TeamID', $data['TeamID']);
                           $this->db->update('Training', $data);
                        }


                    /////////////// вносим данные в таблицу истории
                     
                        $data=$this->_prepare_query($data);
                        $this->db->set($data);
                        $this->db->insert('Training_history');
   
        }
    
    function _renderTable($players)
        {
        $this->load->library('table');

        $tmpl=array
            (
            'table_open'               => '<table class="players_table" cellspacing="0">',
            'row_start'                => '<tr class="alt">',
            'cell_sucsess_start'       => '<td style="background: #00ffff;">',
            'cell_unsucsess_start'     => '<td style="background: #ffcccc;">',
            'cell_alt_sucsess_start'   => '<td style="background: #00ffff;">',
            'cell_alt_unsucsess_start' => '<td style="background: #ffcccc;">',
            );

        $this->table->set_template($tmpl);

        $heading=array
            (
            'ID',
            'Имя игрока',
            'Страна',
            'Результат',
            'Причина'
            );

        $this->table->set_heading($heading);

        foreach ($players as $player)
            {
            if ($player['CountryID'] == 62)
                {
                if ($player['result'])
                    $style='sucsess';
                else
                    $style='unsucsess';

                foreach ($player as $key => $value)
                    {
                    if ($key != 'CountryID')
                        $player[$key]=array
                            (
                            '<b>' . $value . '</b>',
                            $style
                            );
                    }

                $player['CountryID']=array
                    (
                    '<img src="' . site_url() . 'images/countryid/' . $player['CountryID'] . '_mini.gif">',
                    $style
                    );
                }
            else
                $player['CountryID']
                    ='<img src="' . site_url() . 'images/countryid/' . $player['CountryID'] . '_mini.gif">';

            $this->table->add_row($player);
            }

        return $this->table->generate();
        }

    function _prepare_query($data)
        {
        
        if ($this->db->ar_set) 
                $this->db->ar_set=array();
        
        foreach ($data as $key => $value) //убираем NULL значения
            {
            if ($value == NULL)
                $data[$key]='';
            }   
        return $data;
        }
        
    function _getCountryIdByLeagueID() //функция для соответствия страны-лиги стране ИД
        {
        $user="fazzer";
        $pass="fazzer1982";
        $this->load->library('PHT');
        $this->load->config('CHPP');
        $this->HT=new CHPPConnection($this->config->item('CHPP_App_Name'), $this->config->item('CHPP_num'),
                                     $this->config->item('CHPP_key'),      $this->config->item('CHPP_cookie_path'));

        if ($this->auth->ht_login($user, $pass, $this->HT))
            {
            $filelist=glob('images/flags/*.gif');
            $world   =$this->HT->getWorldDetails();

            foreach ($filelist as $file)
                {
                $t    = substr($file, 13);
                $cur  =strpos($t, "_");
                $ID   =(int)substr($t, 0, $cur);
                $newID=$world->getLeagueById($ID)->getCountryId();
                //$tt=$world->getLeagueByCountryId(62)->getId();
                copy($file, 'images/countryid/' . $newID . '_mini.gif');
                }

            $i=0;
            }
        }
    }
?>